package cn.dhnep.demo.controller;


import cn.dhnep.demo.pojo.Classify;
import cn.dhnep.demo.pojo.frontvo.MainClassify;
import cn.dhnep.demo.pojo.vo.RespBean;
import cn.dhnep.demo.pojo.vo.RespPageBean;
import cn.dhnep.demo.service.ClassifyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 产品分类控制器
 * </p>
 *
 * @author dhn
 * @since 2021-08-16
 */
@RestController
@RequestMapping("/dhn/classify")
public class ClassifyController {

    @Resource
    private ClassifyService classifyService;

    @ApiOperation("获取产品分类列表")
    @GetMapping("getAllClassify")
    public RespPageBean getAllClassify(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "15") Integer limit,
                                       @RequestParam(value = "fid", required = false) Integer fid,
                                       @RequestParam(value = "number", required = false) String number,
                                       @RequestParam(value = "name", required = false) String name) {
        return classifyService.pageQueryClassify(page, limit, fid, number, name);
    }

    @ApiOperation("根据id获取产品分类详细信息")
    @GetMapping("getClassifyById")
    public void getClassifyById(Integer id, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Classify classify = classifyService.getById(id);
        request.getSession().setAttribute("classify", classify);
        request.getRequestDispatcher("../../page/product-edit.html").forward(request, response);
    }

    @ApiOperation("渲染产品分类")
    @GetMapping("queryClassify")
    public RespBean queryClassify(HttpServletRequest request) {
        Classify classify = (Classify) request.getSession().getAttribute("classify");
        return RespBean.success(null, classify);
    }

    @ApiOperation("获取所有主分类")
    @GetMapping("getAllMainClassifyName")
    public RespBean getAllMainClassifyName() {
        return RespBean.success(null, classifyService.list(new QueryWrapper<Classify>().eq("fid", 0)));
    }

    @ApiOperation("修改产品分类内容")
    @PutMapping("updateClassify")
    public RespBean updateClassify(@Validated @RequestBody MainClassify mainClassify) {
        //TODO 修改者的名字也不能为空
        if (StringUtils.isEmpty(mainClassify.getId()) || StringUtils.isEmpty(mainClassify.getFid())) {
            return RespBean.error("分类信息不得为空！");
        }
        Classify classify = new Classify();
        BeanUtils.copyProperties(mainClassify, classify);
        classify.setIcon(mainClassify.getFile());
        //TODO 最后修改的时间赋值
        if (classifyService.updateById(classify)) {
            return RespBean.success("修改产品分类内容成功！");
        }
        return RespBean.error("修改产品分类内容失败！");
    }

    @ApiOperation("删除产品分类")
    @DeleteMapping("delClassifyById/{id}")
    public RespBean delClassifyById(@PathVariable Integer id) {
        if (classifyService.removeById(id)) {
            return RespBean.success("删除产品分类成功！");
        }
        return RespBean.success("删除产品分类失败！");
    }

    @ApiOperation("添加主分类")
    @PostMapping("addMainClassify")
    public RespBean addMainClassify(@Validated @RequestBody MainClassify mainClassify) {
        if (StringUtils.isEmpty(mainClassify.getFile())) return RespBean.error("请先上传图片！");
        Classify classify = new Classify();
        BeanUtils.copyProperties(mainClassify, classify);
        classify.setFid(0)
                .setIcon(mainClassify.getFile())
                .setRegistrationTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        if (classifyService.save(classify)) {
            return RespBean.success("主类产品添加成功！");
        }
        return RespBean.error("主类产品添加失败！");
    }

    @ApiOperation("产品分类添加")
    @PostMapping("addChildClassify")
    public RespBean addChildClassify(@Validated @RequestBody MainClassify mainClassify) {
        if (StringUtils.isEmpty(mainClassify.getFile())) return RespBean.error("请先上传图片！");
        Integer fid = mainClassify.getFid(); //产品所属主分类id
        if (StringUtils.isEmpty(fid)) return RespBean.error("产品所属主分类不能为空，请选择主分类！");
        Classify classify = new Classify();
        BeanUtils.copyProperties(mainClassify, classify);
        classify.setFid(fid)
                .setIcon(mainClassify.getFile())
                .setRegistrationTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
        if (classifyService.save(classify)) {
            return RespBean.success("产品主类添加成功！");
        }
        return RespBean.error("产品主类添加失败！");
    }

    @ApiOperation("上传产品分类图片")
    @PostMapping("uploadIcon")
    public RespBean uploadIcon(MultipartFile file) {
        if (StringUtils.isEmpty(file)) throw new RuntimeException("图片不能为空！");

        //String iconPaths = Constant.ICONPATH + "icon/type/";
        //System.out.println(iconPaths);

        /*File files = new File(iconPath);
        if (!files.exists() && !files.isDirectory()) {
            System.out.println("目录不存在，创建目录：" + files);
            //如果目录不存在则创建目录
            files.mkdir();
        }*/

        String iconPathEnum = "F:/data/"; //本地路径
        //获取原始文件名称（包含格式）
        String originalIconName = file.getOriginalFilename();
        System.out.println("原始图片名称：" + originalIconName);

        //获取文件类型，以最后一个'.'为标识
        String iconType = originalIconName.substring(originalIconName.lastIndexOf(".") + 1);
        System.out.println("图片类型为：" + iconType);

        //获取文件名称（不含格式）
        //String iconName = originalIconName.substring(0, originalIconName.lastIndexOf("."));

        //设置文件新名称
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        //iconName = newDate + iconName + "." + iconType;
        String iconName = newDate + "." + iconType;
        System.out.println("新文件名称----------->" + iconName);

        //在指定路径下创建文件
        File targetFile = new File(iconPathEnum, iconName);
        String address = "https://www.dhnep.cn:8181/dhn/icon/type/";

        //将图片保存到指定位置
        try {
            file.transferTo(targetFile);
            System.out.println("上传成功");
            //返回图片的网络路径
            return RespBean.success(null, address + iconName);
        } catch (IOException e) {
            return RespBean.error("图片上传失败！");
        }
    }
}

